package com.example.zjx8969.myapplication

import android.Manifest
import android.app.ActivityOptions
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.text.style.LeadingMarginSpan
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.app.ActivityCompat
import androidx.lifecycle.lifecycleScope
import com.google.android.material.imageview.ShapeableImageView
import com.google.android.material.shape.ShapeAppearanceModel
import com.google.android.material.textview.MaterialTextView
import com.perfect.BannerEntity
import com.perfect.downloader.Downloader
import kotlinx.coroutines.launch
import java.io.File
import java.util.concurrent.CountDownLatch

class RxJavaActivity : BaseActivity(), View.OnClickListener {
    /*  var button: Button? = null
      val txtShow: TextView by lazy { this.findViewById<TextView>(R.id.txtShow) }*/
    private lateinit var container: LinearLayoutCompat
    private lateinit var imageView: ShapeableImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        window.exitTransition = Slide(Gravity.START)
        setContentView(R.layout.activity_rx_java)
        findViewById<View>(R.id.btn1).setOnClickListener(this)
        findViewById<View>(R.id.btn2).setOnClickListener(this)
/*        findViewById<TableLayout>(R.id.custom_color_palette)?.apply {
            addItems(this, arrayOf("1", "2", "3", "4", "5", "6", "7"))
        }*/
//        button = findViewById(R.id.okHttp)
        imageView = findViewById<ShapeableImageView>(R.id.shapeableImageView)
        container = findViewById(R.id.container)

        Log.d("tag", ComponentName(this, BaseActivity::class.java).className)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Log.d("tag", packageManager.backgroundPermissionOptionLabel.toString())
        }
    }


    /*  fun onThreadChangeTestClicked(view: View?) {
          val layoutParams = button!!.layoutParams as RelativeLayout.LayoutParams
          layoutParams.addRule(RelativeLayout.ABOVE, R.id.thread_test)
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
              layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
          }
          button!!.layoutParams = layoutParams
      }*/


    fun onOkHttpClicked(view: View?) {
        val textArray =
                arrayOf(
                        "· Looks beautifully crisp",
                        "· Clear zoom-in image",
                        "· Contains more detail",
                        "· Good print quality"
                )
        val parameters =
                LinearLayoutCompat.LayoutParams(
                        LinearLayoutCompat.LayoutParams.WRAP_CONTENT,
                        LinearLayoutCompat.LayoutParams.WRAP_CONTENT,
                        1f / textArray.size
                )

        val colorSpan = ForegroundColorSpan(Color.BLACK)
        val alignSpan = LeadingMarginSpan.Standard(0, 15)
        textArray.forEachIndexed { index, s ->
            val item = MaterialTextView(container.context).apply {
                id = index
                maxLines = 2
                gravity = Gravity.START or Gravity.CENTER_VERTICAL
                setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13f)
                text = SpannableString(s).apply {
                    setSpan(alignSpan, 0, s.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
                    setSpan(colorSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
                }
            }
            container.addView(item, parameters)
        }


        imageView.shapeAppearanceModel = ShapeAppearanceModel().withCornerSize(6f)

//        QueueDialogModel(lifecycleScope, arrayOf(RequestLocationPermissionDialog::class.java, DialogTask1::class.java)).showNextDialogByOrder()
/*        DialogManagerKt.add()
        AlertDialog.Builder(this).setTitle(R.string.contour_highlight_title).setMessage(R.string.chat_artist_recall_message)
                .setPositiveButton(R.string.com_skip) { dialog, witch ->

                }.setNegativeButton(R.string.vip_features_intercept_get_now) { dialog, witch ->

                }.show()
        val url = "http://api-test.yhouse.com/config/init"*/

    }

    /*
        class RequestLocationPermissionDialog(callBack: QueueDialogModel) :
            QueuedDialogTask<String>(callBack) {
            override fun createDialog(): AbstractQueueDialog? {
                val activity = AppLifeCycleInstance.currentActivity as FragmentActivity? ?: return null
                return Dialog2(activity.supportFragmentManager, this)
            }

            override fun ifConditionSatisfyPre(): Boolean {
                return ContextCompat.checkSelfPermission(
                    App.app,
                    android.Manifest.permission.ACCESS_FINE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED
            }

            class Dialog2(
                fragmentManagers: FragmentManager,
                override var listener: DialogInterface.OnDismissListener
            ) :
                QueueDialogImpByFragment(fragmentManagers, listener) {
                private val requestCode = 1
                override fun onCreate(savedInstanceState: Bundle?) {
                    super.onCreate(savedInstanceState)
                    requestPermissions(
                        arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
                        requestCode
                    )
                }

                override fun onRequestPermissionsResult(
                    requestCode: Int,
                    permissions: Array<out String>,
                    grantResults: IntArray
                ) {
                    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
                    notifyOtherDialogDismiss()
                }
            }
        }


        class DialogTask1(private val callBack: QueueDialogModel) : QueuedDialogTask<String>(callBack) {
            override fun createDialog(): AbstractQueueDialog? {
                val activity = AppLifeCycleInstance.currentActivity as FragmentActivity? ?: return null
                return Dialog1(activity, this)
            }

            inner class Dialog1(
                val context: Context,
                override var listener: DialogInterface.OnDismissListener
            ) :
                AbstractQueueDialog {
                override fun showDialog(): Boolean {
                    AlertDialog.Builder(context).setTitle(R.string.contour_highlight_title)
                        .setMessage(R.string.chat_artist_recall_message)
                        .setOnDismissListener {
                            notifyOtherDialogDismiss()
                        }
                        .setPositiveButton(R.string.com_skip) { dialog, witch ->
                        }.setNegativeButton(R.string.vip_features_intercept_get_now) { dialog, witch ->
                        }.show()
                    return true
                }
            }
        }
    */
    fun onThreadWaitClick(view: View?) {

        startActivity(
                Intent(this, MainActivity::class.java),
                ActivityOptions.makeSceneTransitionAnimation(this)
                        .toBundle()
        )
/*        val latch = CountDownLatch(1)
        LongTimeWaitThread(latch).start()
        try {
            latch.await()
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }*/
    }

    /*fun onKotlinSuspendClick(view: View?) {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE), 1)
            return
        }

        GlobalScope.launch(Dispatchers.Main) {
            val readText = withContext(Dispatchers.IO) {
                File(Environment.getExternalStorageDirectory(), "/.x_o_b_d").readText()
            }
            txtShow.text = readText

        }.invokeOnCompletion { }


    }*/

    internal inner class LongTimeWaitThread(var countDownLatch: CountDownLatch?) : Thread() {
        override fun run() {
            super.run()
            try {
                sleep((Math.random() * 100000).toLong())
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
            if (countDownLatch != null) {
                countDownLatch!!.countDown()
            }
            Log.e("tag", "thread execute done")
        }

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn1 -> {
                val dir = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "banner").absolutePath
                val callback = object : Function3<String, File, Boolean, Unit> {
                    override fun invoke(url: String, file: File, isSuccess: Boolean) {
                        Log.d("tag", "isSuccess:$isSuccess,path=${file.absolutePath},url=$url")
                    }

                }
                lifecycleScope.launch {
                    val banners = loadData<BannerEntity>(assets, "homeBanner.txt", BannerEntity::class.java)
                    val list = banners?.slotList?.filter {
                        it.bannerList != null
                    }?.flatMap {
                        it.bannerList!!
                    } ?: return@launch
                    Log.i("tag", "downloadSize=${list.size}")
                    list.forEach {
                        Log.e("tag", "${it.id}," + it.imageUrl)
                        Downloader.newTask(it.imageUrl, dir, it.imageUrl.substring(1 + it.imageUrl.lastIndexOf("/"))) { url: String, file: File, isSuccess: Boolean ->
                            Log.d("tag", "isSuccess:$isSuccess,path=${file.absolutePath},url=$url")
                        }
                    }
                }
//                createLoadingDialog(this, "title", "content", false).show()
/*                superposedView?.setAvatarUrls(
                        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic4.zhimg.com%2Fv2-b6eae3250bb62fadb3d2527f466cf033_b.jpg&refer=http%3A%2F%2Fpic4.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1632387544&t=30ae18ffc23c6afc4d9161cca81657da",
                        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201710%2F24%2F20171024071632_hzJ8n.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1632387545&t=5cd9be77ba7c67c1d0c35fcb351609f0",
                        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.zhimg.com%2F50%2Fv2-aa86ffb3afa2f36c2bc552d3cb7a8261_hd.jpg&refer=http%3A%2F%2Fpic1.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1632387545&t=d80077947c0b1028ac18e5fa9d1c6bb0",
                        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201509%2F27%2F20150927200243_YmaQB.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1632387545&t=c606bb8e12adb2ce9c5a7c8af57a9634",
                        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201508%2F18%2F20150818213048_vAdhz.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1632387545&t=82551e54547f18186b05f538c8159d0b",
                        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201709%2F16%2F20170916201828_8R5fw.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1632387545&t=6a24e3e88e792e5059a17eac81c6559a",
                        "https://avatars1.githubusercontent.com/u/54600848?v=4",
                        "https://img-blog.csdnimg.cn/20201014180756927.png?x-oss-process=image/resize,m_fixed,h_64,w_64"
                )*/
/*                if (ContextCompat.checkSelfPermission(
                        this,
                        android.Manifest.permission.ACCESS_FINE_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    ActivityCompat.requestPermissions(
                        this,
                        arrayOf(
                            android.Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION
                        ),
                        1
                    )
                }*/

            }
            R.id.btn2 -> {
                ActivityCompat.requestPermissions(
                        this,
                        arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION),
                        2
                )
/*                AlertDialog.Builder(this).setMessage(R.string.contour_highlight_desc)
                    .setNegativeButton(R.string.com_confirm) { dialog, which ->
                        ActivityCompat.requestPermissions(
                            this,
                            arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION),
                            2
                        )
                    }
                    .setPositiveButton(R.string.com_skip) { dialog, _ -> dialog.dismiss() }
                    .show()*/
/*                if (ContextCompat.checkSelfPermission(
                        this,
                        android.Manifest.permission.ACCESS_FINE_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
                        this,
                        android.Manifest.permission.ACCESS_BACKGROUND_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        arrayOf(
                            android.Manifest.permission.ACCESS_FINE_LOCATION,
                            android.Manifest.permission.ACCESS_BACKGROUND_LOCATION
                        )
                    } else {
                        arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION)
                    }
                    ActivityCompat.requestPermissions(
                        this,
                        permissions,
                        2
                    )
                }*/
            }
        }
    }

    override fun onRequestPermissionsResult(
            requestCode: Int,
            permissions: Array<out String>,
            grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        permissions.forEachIndexed { index, s ->
            Log.e("tag", "$s ${grantResults[index] == PackageManager.PERMISSION_GRANTED}")
        }
    }
}